//
//  MMMovableView.m
//  MemeMaker
//
//  Created by Phan Quang Ha on 7/9/13.
//  Copyright (c) 2013 soyo. All rights reserved.
//

#import "MMMovableView.h"
#import "MMConstants.h"

@implementation MMMovableView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
//        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanAction:)];
        UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchAction:)];
//        [self addGestureRecognizer:panGesture];
        [self addGestureRecognizer:pinchGesture];
        
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    [super drawRect:rect];
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
    CGContextFillRect(context, rect);
    
    CGContextSetLineWidth(context, 1.0);
    CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor);
    CGContextStrokeRect(context, rect);
    CGContextFlush(context);
}

#pragma mark - Gesture actions
- (void) handlePanAction:(UIPanGestureRecognizer *)reg
{
    CGPoint translation = [reg translationInView:self.superview];
    self.center = CGPointMake(self.center.x + translation.x, self.center.y + translation.y);
    [reg setTranslation:CGPointZero inView:self.superview];
    [self setNeedsDisplay];
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_UPDATE_PREVIEWING_PICTURE object:nil];
}
- (void) handlePinchAction:(UIPinchGestureRecognizer *)reg
{
    CGAffineTransform transform = CGAffineTransformMakeScale(reg.scale, reg.scale);
    self.bounds = CGRectApplyAffineTransform(self.bounds, transform);
    
//    self.transform = CGAffineTransformScale(self.transform, reg.scale, reg.scale);
    
    reg.scale = 1;
    
    [self setNeedsDisplay];
}

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint curPoint = [touch locationInView:self];
    CGPoint previousPoint = [touch previousLocationInView:self];
    
    self.center = CGPointMake(self.center.x + (curPoint.x - previousPoint.x), self.center.y + (curPoint.y - previousPoint.y));
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_UPDATE_PREVIEWING_PICTURE object:nil];
}

@end
